package org.example.nio;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;

/**
 * <p>  </p>
 *
 * @author Chris
 * @since 2024/3/23 15:18
 */
public class TimeClientHandler implements Runnable {
    /**
     * 使用 slf4j 日志框架
     */
    private final static Logger log = LoggerFactory.getLogger(TimeClientHandler.class);

    private final String host;
    private final int port;
    private Selector selector;
    private SocketChannel socketChannel;
    private volatile boolean stop;

    public TimeClientHandler(String host, int port) {
        this.host = (StringUtils.isBlank(host) ? "127.0.0.1" : host);
        this.port = port;
        try {
            this.selector = Selector.open();
            this.socketChannel = SocketChannel.open();
            this.socketChannel.configureBlocking(false);
        } catch (IOException e) {
            log.error("error=", e);
            System.exit(1);
        }

    }

    @Override
    public void run() {
        try {
            this.doConnect();
        } catch (Exception e) {
            log.error("error=", e);
            System.exit(1);
        }

        while (!this.stop) {
            try {
                // 每 1 秒轮询一次
                this.selector.select(1000);
                // 遍历就绪的连接
                for (SelectionKey key : this.selector.selectedKeys()) {
                    try {
                        this.handleInput(key);
                    } catch (IOException e) {
                        log.error("error=", e);
                        key.cancel();
                        if (key.channel() != null) {
                            key.channel().close();
                        }
                    } finally {
                        this.selector.selectedKeys().remove(key);
                    }
                }
            } catch (IOException e) {
                log.error("error=", e);
                System.exit(1);
            }
        }

        // 关闭多路复用器
        if (this.selector != null) {
            try {
                this.selector.close();
            } catch (IOException e) {
                log.error("error=", e);
            }
        }
    }

    private void doConnect() throws IOException {
        // 连接后注册到多路复用器
        if (this.socketChannel.connect(new InetSocketAddress(this.host, this.port))) {
            this.socketChannel.register(this.selector, SelectionKey.OP_READ);
            // 发送请求
            this.doWrite(socketChannel);
        } else {
            // 没有立即连接成功，则注册 “OP_CONNECT” 状态，待稍后多路复用器轮询其连接状态。
            this.socketChannel.register(this.selector, SelectionKey.OP_CONNECT);
        }
    }

    private void handleInput(SelectionKey key) throws IOException {
        if (!key.isValid()) {
            return;
        }

        SocketChannel sc = (SocketChannel) key.channel();
        if (key.isConnectable()) {
            if (sc.finishConnect()) {
                sc.register(this.selector, SelectionKey.OP_READ);
                // 写指令
                this.doWrite(sc);
            } else {
                System.exit(1);
            }
        }

        if (key.isReadable()) {
            final ByteBuffer readBuffer = ByteBuffer.allocate(1024);
            final int readBytes = sc.read(readBuffer);
            if (readBytes > 0) {
                readBuffer.flip();
                final byte[] bytes = new byte[readBuffer.remaining()];
                readBuffer.get(bytes);
                final String body = new String(bytes, StandardCharsets.UTF_8);
                log.info("Now is: {}", body);

                this.stop = true;
            } else {
                if (readBytes < 0) {
                    key.cancel();
                    sc.close();
                }
            }
        }

    }

    private void doWrite(SocketChannel socketChannel) throws IOException {
        byte[] req = "QUERY TIME ORDER".getBytes();
        final ByteBuffer writeBuffer = ByteBuffer.allocate(req.length);
        writeBuffer.put(req);
        writeBuffer.flip();
        socketChannel.write(writeBuffer);
        if (!writeBuffer.hasRemaining()) {
            log.info("Send order 2 server succeed.");
        }
    }


}